package com.zcsy.manage.service.system.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.zcsy.commons.constants.Constants;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.system.Menu;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.system.MenuDao;
import com.zcsy.manage.service.common.CommonService;
import com.zcsy.manage.service.system.IMenuService;
import com.zcsy.manage.service.system.IRoleService;


/**
 * @ClassName: MenuServiceImpl
 * @Description: TODO
 * @author tanghan barbadosliy@163.com
 * @date 2015年2月1日 下午3:51:23
 *
 */
@Service
public class MenuServiceImpl extends SystemComService implements IMenuService{
	
	@Autowired
	private MenuDao menuDao;
	
	@Autowired
	private Mapper mapper;
	
	@Autowired 
	private IRoleService roleService;

	/* (non-Javadoc)
	 * @see com.framework.service.IMenuService#getMenuByState(java.lang.Integer)
	 */
	@Override
	public List<Menu> getMenuByState(Integer state) {
		return menuDao.getMenuByState(state);
	}

	/*
	 * (non-Javadoc)
	 * @see com.zcsy.shop.service.system.IMenuService#getMenuByPId(java.lang.Integer, int)
	 */
	@Override
	public List<Menu> getMenuByPId(String pid , String roleId) {
	    List<Menu> result = new ArrayList<Menu>();
	    Map<String , Object> map = new HashMap<String, Object>();
	    map.put("pid", pid);
	    map.put("roleId", roleId);
	    List<Menu> menus = menuDao.getMenuByPIdAndRole(map);
	    if(CollectionUtils.isNotEmpty(menus)){
	        for(Menu menu :menus){
	            List<Menu> submenus = getSubMenus(menu , roleId);
	            int subCount = menuDao.getSubMenuCount(menu.getId());
	            
	            //有权限的子菜单不为空
	            if((!StringUtils.isEmpty(pid) && subCount == 0) || CollectionUtils.isNotEmpty(submenus)){
	                menu.setSubMenus(submenus);
	            	result.add(menu);
	            }
	        }
	    }
	    
		return result;
	}
	
	private List<Menu> getSubMenus(Menu menuVo , String roleId){
		Map<String , Object> map = new HashMap<String, Object>();
	    map.put("pid", menuVo.getId());
	    map.put("roleId", roleId);
	    List<Menu> menus = menuDao.getMenuByPIdAndRole(map);
	    if(CollectionUtils.isNotEmpty(menus)){
	        List<Menu> submenus = new ArrayList<Menu>();
	        for(Menu menu:menus){
	            List<Menu> sub = getSubMenus(menu , roleId);
	            int subCount = menuDao.getSubMenuCount(menu.getId());
	          
	            //有权限的子菜单不为空
	            if(subCount == 0 || CollectionUtils.isNotEmpty(sub)){
	                menu.setSubMenus(sub);
	            }
	        }
	        return submenus;
	    }
	    return null;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.zcsy.shop.service.system.IMenuService#getMenuById(java.lang.Integer)
	 */
	@Override
    public Menu getMenuById(String id){
        return menuDao.getMenuById(id);
    }

    /* (non-Javadoc)
	 * @see com.framework.service.IMenuService#insert(com.framework.model.Menu)
	 */
	@Override
	public int insert(Menu record) {
		return menuDao.insert(record);
	}

	/* (non-Javadoc)
	 * @see com.framework.service.IMenuService#updateByPrimaryKey(com.framework.model.Menu)
	 */
	@Override
	public int updateByPrimaryKey(Menu record) {
		Menu oldMenu = menuDao.getMenuById(record.getId());

		oldMenu.setType(record.getType());
		oldMenu.setMenuName(record.getMenuName());
		oldMenu.setLocationURL(record.getLocationURL());
		oldMenu.setMenuLevel(record.getMenuLevel());
		oldMenu.setMenuOrder(record.getMenuOrder());
		oldMenu.setParentId(record.getParentId());
		oldMenu.setSystem(record.getSystem());
		oldMenu.setMenuType(record.getMenuType());
		oldMenu.setValue(record.getValue());
		
		return menuDao.updateByPrimaryKey(oldMenu);
	}

	/*
	 * (non-Javadoc)
	 * @see com.zcsy.shop.service.system.IMenuService#queryByLocationURL(java.lang.String)
	 */
	@Override
	public Menu queryByLocationURL(String locationURL) {
	    Menu menu = menuDao.queryByLocationURL(locationURL);
	    if(menu.getMenuLevel() ==3){
	        Menu parentMenu = menuDao.getMenuById(menu.getParentId());
            return parentMenu;
	    }else{
	        return menu;
	    }
	}

	/* (non-Javadoc)
	 * @see com.framework.service.IMenuService#queryMenuByRoleId(java.lang.Integer)
	 */
	@Override
	public List<Menu> queryMenuByRoleId(String roleId) {
		return menuDao.queryMenuByRoleId(roleId);
	}
	
	@Override
	public List<Menu> queryFunctionsByRoleId(String roleId) {
		return menuDao.queryFunctionsByRoleId(roleId);
	}

    /* (non-Javadoc)
     * @see com.framework.service.IMenuService#queryMenu(com.framework.model.Menu)
     */
    @Override
    public List<Menu> queryMenu(Menu record){
        return menuDao.queryMenu(record);
    }

    /*
     * (non-Javadoc)
     * @see com.zcsy.shop.service.system.IMenuService#updateMenuState(int, int)
     */
    @Override
    public void updateMenuState(String menuId, int state) {
        Menu menu = menuDao.getMenuById(menuId);
        menu.setState(state);
        menuDao.updateByPrimaryKey(menu);

        if(state == Constants.MENU_STATE_DISABLED){
        	stopSubMenus(menu);            
        }
        
    }
    
    /**
      * @Title: stopSubMenus
      * 停用的，停用上级菜单，则对应的下级菜单均停用，
      * 启用时，启用上级菜单，对应下级菜单不一起启用
      * @param menu    设定文件
      * @return void    返回类型
      * @throws
      */
    private void stopSubMenus(Menu menu){
    	List<Menu> submenus = menuDao.getMenuByPId(menu.getId());
    	if(CollectionUtils.isNotEmpty(submenus)){
    		for(Menu sub:submenus){
    			sub.setState(Constants.MENU_STATE_DISABLED);
    			menuDao.updateByPrimaryKey(sub);
    			//停用下级菜单
    			stopSubMenus(sub);
    		}
    	}
    }
    
    /*
     * (non-Javadoc)
     * @see com.zcsy.shop.service.system.IMenuService#getMenusByCache(com.zcsy.shop.model.system.User)
     */
	@Override
	public List<Menu> getMenusByCache(User user , Integer type) {
	    
	    List<Menu> result = getMenusByComCache(user , type);
		
		return result;
	}
	
	 /*
     * (non-Javadoc)
     * @see com.zcsy.shop.service.system.IMenuService#getMenusByCache(com.zcsy.shop.model.system.User)
     */
	@Override
	public List<Menu> getMenusArrayByCache(User user,Integer type) {
	    
	    List<Menu> result = getMenusArrayByComCache(user,type);
		
		return result;
	}
	
	@Override
	public Menu getFirstAvailableMenus(List<Menu> menus){
		return super.getFirstAvailableMenus(menus);
	}
	
	

	/** 
     * @Title: getFirstParentMenu 
     * @Description: 获取某制定菜单的父菜单(一级或二级)
     * @param @param menus
     * @param @param parentId
     * @param @return     
     * @return Menu     
     * @throws 
     */
	public static Menu getParentMenuStatic(List<Menu> menus , String parentId){
		for(Menu item : menus){
			if(item.getId().equals(parentId)){
				return item;
			}
		}
		
		return null;
	}

	 /**
     * 根据地址获取菜单
     * 
     * @param uri
     * @param menus
     * @return
     */
	public static Menu getMenuByUriStatic(String uri, List<Menu> menus) {
		// TODO Auto-generated method stub
		for (Menu item : menus) {
			if (!StringUtils.isEmpty(item.getLocationURL()) && uri.contains(item.getLocationURL())
					&& (item.getSubMenus() == null || item.getSubMenus().size() == 0)
					) {
				return item;
			}
		}
		
		return null;
	}
	
	/**
     * 根据地址获取菜单
     * 
     * @param uri
     * @param menus
     * @return
     */
    public static Menu getMenuByUriAll(String uri, List<Menu> menus) {
        // TODO Auto-generated method stub
    	String urlString = null;
        for (Menu item : menus) {
        	urlString = "/seller" + item.getLocationURL();
            if (!StringUtils.isEmpty(item.getLocationURL()) && uri.equals(urlString)) {
                return item;
            }
        }
        
        return null;
    }

	@Override
	public List<Menu> getAllBySystem(Integer system) {
		// TODO Auto-generated method stub
		return menuDao.getAllBySystem(system);
	}

	@Override
	public List<Menu> getAllLeaves(Integer system) {
		// TODO Auto-generated method stub
		return menuDao.getAllLeaves(system);
	}

	@Override
	public int insertButton(Menu record) {
		// TODO Auto-generated method stub
		return menuDao.insertButton(record);
	}
	
	@Override
	public boolean initUserFirstMenuBycell(User user , Integer type){
		for(int i = 0 ; i < user.getCellInfos().size() ; i ++){
			CellInfo item = user.getCellInfos().get(i);
			//取出当前用户在当前小区的角色集合
			List<String> roleCellList = roleService.getRoleListBycellId(item.getId(),user.getId());
			user.setRoleCellList(roleCellList);
			
			List<Menu> menus = getMenusByCache(user , type);
			if (CollectionUtils.isEmpty(menus)){
			 	continue;
			}
            
			//取出第一个有效的一级菜单
			Menu first = getFirstAvailableRootMenus(menus);
			if (first == null){
			 	continue;
			}
			
			user.setCellBtns(getBtnsByComCache(user , type));
			user.setCellMenus(menus);
            user.setMenu(first);
            user.setCurrentCell(item);//设置为当前小区
            
            return true;
		}
		
		return false;
	}
	
	@Override
	public boolean initAdminUserFirstMenu(User user, Integer type) {

		List<Menu> menus = getMenusByComCache(user, type,
				Constants.MENU_TYPE_PLATFORM);
		if (CollectionUtils.isEmpty(menus)) {
			return false;
		}

		// 取出第一个有效的一级菜单
		Menu first = getFirstAvailableRootMenus(menus);
		if (first == null) {
			return false;
		}

		user.setCellBtns(getBtnsByComCache(user , type));
		user.setCellMenus(menus);
		user.setMenu(first);

		return true;
	}
	
	@Override
	public boolean updateUserFirstMenuBycell(User user , Integer type , String cellId){
		for(int i = 0 ; i < user.getCellInfos().size() ; i ++){
			CellInfo item = user.getCellInfos().get(i);
			if(cellId.equals(item.getId())){
			//取出当前用户在当前小区的角色集合
			List<String> roleCellList = roleService.getRoleListBycellId(item.getId(),user.getId());
			user.setRoleCellList(roleCellList);
			
			List<Menu> menus = getMenusByCache(user , type);
			if (CollectionUtils.isEmpty(menus)){
			 	return false;
			}
            
			//取出第一个有效的一级菜单
			Menu first = getFirstAvailableRootMenus(menus);
			if (first == null){
				return false;
			}
			
			user.setCellBtns(getBtnsByComCache(user , type));
			user.setCellMenus(menus);
            user.setMenu(first);
            user.setCurrentCell(item);//设置为当前小区
            CommonService.setSessionMenusArray(getMenusArrayByComCache(user,type));
			
            return true;
			}
		}
		
		return false;
	}
	
	@Override
	public boolean updateAdminUserFirstMenu(User user, Integer type , String cellId) {
		if(StringUtils.isEmpty(cellId)){
			List<Menu> menus = getMenusByComCache(user, type,
					Constants.MENU_TYPE_PLATFORM);
			if (CollectionUtils.isEmpty(menus)) {
				return false;
			}

			// 取出第一个有效的一级菜单
			Menu first = getFirstAvailableRootMenus(menus);
			if (first == null) {
				return false;
			}

			user.setCellBtns(getBtnsByComCache(user , type));
			user.setCellMenus(menus);
			user.setMenu(first);
			user.setCurrentCell(null);
			CommonService.setSessionMenusArray(getMenusArrayByComCache(user,Constants.SYSTEM_OPERATION_WEB , Constants.MENU_TYPE_PLATFORM));
			
            return true;
		}
		
		for(int i = 0 ; i < user.getCellInfos().size() ; i ++){
			CellInfo item = user.getCellInfos().get(i);
			if(cellId.equals(item.getId())){
				List<Menu> menus = getMenusByComCache(user, type);
				if (CollectionUtils.isEmpty(menus)) {
					return false;
				}

				// 取出第一个有效的一级菜单
				Menu first = getFirstAvailableRootMenus(menus);
				if (first == null) {
					return false;
				}

				user.setCellBtns(getBtnsByComCache(user , type));
				user.setCellMenus(menus);
				user.setMenu(first);
				user.setCurrentCell(item);//设置为当前小区
				CommonService.setSessionMenusArray(getMenusArrayByComCache(user,type));
				
				return true;
			}
		}
		
		return false;
	}
	
	public List<Menu> getMenusByRoleIds(Integer system , List<String> roles){
		HashMap<String , Object> map = new HashMap<String , Object>();
        map.put("roleIds", roles);
        map.put("system", system);
        return menuDao.queryMenuByRoleIds(map);
	}
}
